package com.iha.pongzor.logic;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.iha.pongzor.R;
import com.iha.pongzor.data.HighScore;
import com.iha.pongzor.gui.Menu;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.Vibrator;
import android.widget.Toast;

public class HighscoreChecker extends Service {
	private static final long INTERVAL = 5000;

	private int highestscore = 0;
	private Timer timer = new Timer();

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		startservice();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopservice();
	}

	private void startservice() {
		Toast.makeText(getApplicationContext(), "highscore checker service is started", Toast.LENGTH_SHORT).show();

		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				List<HighScore> highscore = AppHelper.fetchHighscore();

				for (int i = 0; i < highscore.size(); i++) {

					int currentscore = highscore.get(i).getScore();
					if (currentscore > highestscore) {
						Notifier(highscore.get(i));
						highestscore = currentscore;
					}
				}
			}
		}, 0, INTERVAL);
		;
	}

	private void stopservice() {
		if (timer != null) {
			Toast.makeText(getApplicationContext(), "highscore checker service is stopped", Toast.LENGTH_SHORT).show();
			timer.cancel();
		}
	}

	private void Notifier(HighScore newHighscore) {

		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(1000);

		final int notificationID = 10;
		final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// Create the notification
		final Notification notification = new Notification(R.drawable.ic_launcher, "New highscore!! " + newHighscore.getName() +" is king of the hill", System.currentTimeMillis());
		// Create the notification's expanded message
		// When the user clicks on it, it opens your activity
		Intent intent = new Intent(this, Menu.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		notification.setLatestEventInfo(this, "PongZor", "Try to beat " + newHighscore.getName() + "'s " + newHighscore.getScore(), pendingIntent);
		// Show notification
		notificationManager.notify(notificationID, notification);
	}
}
